<?php
function addfile($file_feild)
{	
	$picname = $_FILES[$file_feild]['name'];
	$picsize = $_FILES[$file_feild]['size'];
	if ($picname != "") {
		if ($picsize > 10240000) {
			echo 'Pic can not bigger than 1M';
			die();
		}
		$file_type = strstr($picname, '.');
		if ("$file_type" != ".gif" && "$file_type"  != ".jpg" && "$file_type"  != ".png" && "$file_type"  != ".bmp") {
			echo 'Wrong format file, only allowed .gif, .jpg, .png, .bmp.';
			die();
		}
		$rand = rand(100, 999);
		$pics = date("YmdHis") . $rand . $file_type;
		$pic_path = "../upload/". $pics;
		move_uploaded_file($_FILES[$file_feild]['tmp_name'], $pic_path);
		
		$pic_path = "upload/". $pics;
	}else{
		echo "No image selected";
	}
	return $pic_path;
}


function delete_pic_by_id($id_resto){

	mysql_connect(DBADDR, DBUSER, DBPWD)or die("cannot connect");
	mysql_select_db(DBNAME)or die("cannot select DB");
	mysql_query('set names utf8'); 
	$sql = "SELECT PIC_LOCATION from resto_pic WHERE RESTO_ID='".$id_resto."'";
	$rs_result = mysql_query ($sql);
	if (!$rs_result) {
		echo 'Could not run query: ' . mysql_error();
		die();
	}
	while ($row = mysql_fetch_assoc($rs_result)) { 
		delete_file($row['PIC_LOCATION']);
	}
	
	$sql = "SELECT INTRO_PIC from info_resto WHERE RESTO_ID='".$id_resto."'";
	$rs_result = mysql_query ($sql);
	if (!$rs_result) {
		echo 'Could not run query: ' . mysql_error();
		die();
	}
	while ($row = mysql_fetch_assoc($rs_result)) { 
		delete_file($row['INTRO_PIC']);
	}
	
	$sql= "DELETE FROM resto_pic WHERE RESTO_ID='".$id_resto."'";
	$rs_result = mysql_query ($sql);
	if (!$rs_result) {
		echo 'Could not run query: ' . mysql_error();
		die();
	}
}


function delete_file($file_loc){
	if (file_exists($file_loc)) {
		unlink($file_loc);
	}else if(file_exists("../".$file_loc)) {
		unlink("../".$file_loc);
	}
}
?>